<template>
	<!-- 智助智能客服 (学生) -->
	<view class="container">
		<scroll-view scroll-y="true" class="msg-content" :scroll-into-view="scrollToView" @scrolltoupper="loadHistory">
			<view class="content" v-for="(itme,key) in datas" :key="key">
				<!-- 当前聊天时间 -->
				<view class="time" v-if="itme.records.length>1">
					<text>{{itme.sendTime}}</text>
				</view>
				<view v-for="(message,index) in itme.records" :key="index" :id="'msg'+key+index">

					<!-- 客服发送的消息 -->

					<view class="msg-left" v-if="message.accpetAccount === userInfo.username">
						<view class="avatar">
							<image src="../../static/image/customerServiceAvatar.png" mode=""></image>
						</view>
						<view class="msg_content" v-if="message.msgType==1">
							<view class="item"></view>
							<view class="message">
								<text>{{message.chatMsg}}</text>
							</view>
						</view>
						<view class="msg_content" v-if="message.msgType==2">
							<image class="img" :src="message.chatMsg"></image>
						</view>
						<view class="msg_content" v-if="message.msgType==3">
							<view class="item"></view>
							<view class="vediomessage play">
								<i class="iconfont  iconyuyin-jieshou"></i>
								<text>{{message.chatMsg}}</text>
							</view>
						</view>

					</view>
					<view class="msg-right" v-if="message.sendAccount === userInfo.username">
						<!-- 文本 -->
						<view class="msg_content" v-if="message.msgType==1">

							<view class="message">
								<text>{{message.chatMsg}}</text>
							</view>
							<view class="item"></view>
						</view>
						<!-- 图片 -->
						<view class="msg_content" v-if="message.msgType==2">
							<image class="img" :src="message.chatMsg"></image>
						</view>
						<!-- 语言消息 -->
						<view class="msg_content" v-if="message.msgType==3">
							<view class="vediomessage play" @tap="playVoice(message.chatMsg)">
								<!-- <text>{{message.chatMsg}}</text> -->
								<i class="iconfont  iconyuyin-fasong"></i>
							</view>
							<view class="item"></view>
						</view>
						<!-- 头像 -->
						<view class="avatar customerAvatar">
							<image :src="userInfo.avatar" mode=""></image>
						</view>
					</view>
				</view>
				<!-- <view class="msg-left model-flex">
					<view class="avatar">
						<image src="../../static/image/customerServiceAvatar.png" mode=""></image>
						<view class="item"></view>
					</view>
					<view class="model-message">
						<text class="title">推荐分类</text>
						<view class="message-list">
							<span class="dian"></span>
							<navigator class="message" url="./">快速试用教程</navigator>
						</view>
						<view class="message-list">
							<span class="dian"></span>
							<navigator class="message" url="./">快速试用教程</navigator>
						</view>
					</view>
				</view> -->
				<!-- 我的发送的消息 -->
				<!-- 语音 -->
				<!-- <view class="msg-right">
					<view class="message customer-message">
						<text>10"</text>
						<image style="height:28upx;width:20upx;" src="../../static/image/yuyin.png"></image>
					</view>
					<view class="avatar customerAvatar">
					<view class="item"></view>
						<image src="../../static/image/customerAvatar.png" mode=""></image>
					</view>
				</view> -->
				<!-- <view class="msg-left model-flex">
					<view class="avatar">
						<image src="../../static/image/customerServiceAvatar.png" mode=""></image>
						<view class="item"></view>
					</view>
					<view class="model-message">
						<text class="title">为你找到以下内容</text>
						<view class="message-list">
							<span class="dian"></span>
							<navigator class="message" url="./">2018年广东省高考语文试卷</navigator>
						</view>
						<view class="message-list">
							<span class="dian"></span>
							<navigator class="message" url="./">2018年广东省高考语文试卷</navigator>
						</view>
						<view class="message-list">
							<span class="dian"></span>
							<navigator class="message" url="./">2018年广东省高考语文试卷</navigator>
						</view>
						<view class="feedback">
							<text>问题没有解决?</text>
							<navigator url="">前往反馈</navigator>
						</view>
					</view>
				</view> -->
			</view>
		</scroll-view>
		<!-- 底部发送消息 -->
		<view class="information">
			<!-- 语音按钮 -->
			<view :class="['iconfont','iconyuyin',{'iconbianji1':isShowVoice}]" @tap="showVoice"></view>
			<view class="voice-button" type="default" v-if="isShowVoice" @touchstart="voiceBegin" @touchmove.stop.prevent="voiceIng"
			 @touchend="voiceEnd" @touchcancel="voiceCancel">{{voiceTis}}</view>
			<input class="chat" type="text" v-model="chatMessage" v-else />
			<!-- ＋ -->
			<view class="iconfont iconxinjianbijibenjiahao" @tap="showMenu"></view>
			<view class="send" @tap="sendMsg(1)">发送</view>
		</view>
		<!-- 底部发送消息 -->
		<!-- 点击加号弹出 -->
		<view class="addShow" v-show="isShowMenu">
			<view @click="chooseImage(0)" class="addShowImg">
				<view class="iconfont iconxiangce"></view>
				照片
			</view>
			<view @click="chooseImage(1)" class="addShowPhoto">
				<view class="iconfont iconpaishe"></view>
				拍照
			</view>
		</view>
		<!-- 语音提示框 -->
		<!-- 	<view class="voice-container" v-if="voiceObj.voiceTime">
			<view class="iconfont iconyuyin1"></view>
			<text class="voice-time">{{voiceObj.voiceTime}}</text>
		</view> -->

		<!-- 录音UI效果 -->
		<view class="record" :class="recording?'':'hidden'">
			<view class="ing" :class="willStop?'hidden':''">
				<view class="iconfont iconyuyin-mian"></view>
			</view>
			<view class="cancel" :class="willStop?'':'hidden'">
				<view class="iconfont iconquxiaoluyin"></view>
			</view>
			<view class="tis" :class="willStop?'change':''">{{recordTis}}</view>
		</view>
		<!-- 语音提示框 -->
	</view>
</template>


<script>
	var sourceType = [
		['album'],
		['camera'],
		['camera', 'album']
	]
	var sizeType = [
		['compressed'],
		['original'],
		['compressed', 'original']
	]
	export default {

		data() {

			return {
				date: '',
				sourceType: ['拍照', '相册', '拍照或相册'],
				sizeType: ['压缩', '原图', '压缩或原图'],
				sourceTypeIndex: 2,
				sizeTypeIndex: 2,
				uploadurl: '',
				isShowMenu: false,
				isShowVoice: false,
				AUDIO: uni.createInnerAudioContext(),
				playMsgid: null,
				VoiceTimer: null,
				initPoint: {
					identifier: 0,
					Y: 0
				},
				// #ifndef H5
				//H5不能录音
				RECORDER: uni.getRecorderManager(),
				// #endif
				recording: false,
				willStop: false,
				recordTis: "手指上滑 取消发送",
				voiceTis: "按住 说话",
				recordTimer: null,
				recordLength: 0,
				// 链接后返回的对象
				socketTask: {},
				userInfo: {},
				k_token: '',
				chatMessage: '',
				accpetAccount: '',

				// 发送的信息跟接收的信息
				messagelist: [],
				scrollToView: '',
				page: 1,

				datas: [],
				time: ''

			}
		},
		onBackPress() {
			this.socketTask.close();
		},
		onPullDownRefresh() {
			this.page = this.page + 1;
			this.getHistory();
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 500);
		},
		onLoad() {
			this.date = Date.parse(new Date()) / 1000;
			var date = new Date();
			this.time = date.format("yyyy-MM-dd HH:mm:ss");
			this.k_token = uni.getStorageSync('token');
			this.userInfo = uni.getStorageSync('userInfo');


			// 创建服务
			this.createStock();

			//语音自然播放结束
			this.AUDIO.onEnded((res) => {
				this.playMsgid = null;
			});
			// #ifndef H5
			//录音开始事件
			this.RECORDER.onStart((e) => {
				this.recordBegin(e);
			})
			//录音结束事件
			this.RECORDER.onStop((e) => {
				this.recordEnd(e);
			})
			// #endif
		},
		methods: {
			/* 创建连接 */
			createStock() {
				this.socketTask = uni.connectSocket({
					url: 'ws://api1.zhizhuedu.net.cn:8003/ws',
					header: {
						'Authorization': this.k_token
					},
					success: (res) => {}
				})
				this.socketTask.onOpen(() => {
					// 第一次链接的时候发送 action为1 schoolId必传
					this.sendMessageObj = {
						sendAccount: this.userInfo.username,
						schoolId: 177,
						action: 1,
						reqMethod: 1,
						Authorization: this.k_token
					}
					let objStr = JSON.stringify(this.sendMessageObj)
					this.socketTask.send({
						data: objStr,
						success: (res) => {
							// 初始化新数据存储对象
							var data = {
								sendTime: this.time,
								records: []
							}
							this.datas.push(data);
							//获取聊天记录
							this.getHistory();
							//开始监听消息接收
							this.listenMessage()
						}
					})
				})
			},
			// 监听服务端传递的消息
			listenMessage: function() {
				this.socketTask.onMessage((e) => {
					let obj = JSON.parse(e.data)
					if (obj.code == 203) {
						uni.showToast({
							title: '暂无客服在线！',
							icon:'none'
						});
						return;
					}
					if (obj.date.sendAccount) {
						this.accpetAccount = obj.date.sendAccount
					}
					if (obj.date.msgType) {
						//接收消息追加进去
						this.datas[this.datas.length - 1]['records'].push(obj.date);
						console.log(this.datas);
						/* 设置滚动到当前信息 */
						this.$nextTick(function() {
							this.scrollToView = 'msg' + (this.datas.length - 1) + (this.datas[this.datas.length - 1]['records'].length -
								1);
						});
					}
				})
			},
			// 发送消息
			sendMsg(msgType) {
				if (this.accpetAccount == '') {
					uni.showToast({
						title: '暂无客服在线，请退出稍后再试',
						icon:'none'
					});
				} else {

					var obj = {
						sendTime: this.date,
						accpetAccount: this.accpetAccount,
						sendAccount: this.userInfo.username,
						aschoolId: 177,
						reqMethod: 1,
						action: 2,
						msgType: msgType
					}
					switch (msgType) {
						case 1:
							obj.chatMsg = this.chatMessage;
							break;
						case 2:
							obj.chatMsg = this.uploadurl;
							break;
						case 3:
							obj.chatMsg = this.uploadurl;
							break;
					}
					
					if (this.chatMessage||this.uploadurl) {
						this.socketTask.send({
							data: JSON.stringify(obj),
							success: (res) => {
								//发送消息追加进去
								this.datas[this.datas.length - 1]['records'].push(obj);
								console.log(this.datas);
								/* 设置滚动到当前信息 */
								this.$nextTick(function() {
									this.scrollToView = 'msg' + (this.datas.length - 1) + (this.datas[this.datas.length - 1]['records'].length -
										1);
								});
								this.chatMessage = ''
							}
						});
					}
				}
			},
			/* 下拉加载聊天记录 */
			loadHistory: function() {
				this.page = this.page + 1;
				this.getHistory();
			},
			/* 获取聊天记录 */
			getHistory: function() {
				var _this = this;
				var data = {
					chatTime: this.time,
					sendAccount: this.userInfo.username,
					schoolId: 177,
					reqMethod: 1,
					page: this.page,
					pageSize: 3
				};
				this.$kapi.apiPost('customerService/selChatRecords', data).then(res => {
					var data = res.data;
					if (data.code == 200) {
						var list = data.date;
						_this.$nextTick(function() {
							// 滚动到底
							_this.scrollToView = 'msg' + (list.length - 1) + (list[list.length - 1]['records'].length - 1)
							_this.datas = list.concat(_this.datas);
							console.log(_this.datas);
						});
					}
				});
			},
			/* 上传图片 */
			chooseImage: function(index) {
				var _this = this;
				uni.chooseImage({
					count: 1, //默认9
					sourceType: sourceType[index],
					sizeType: sizeType[this.sizeTypeIndex],
					success: function(res) {
						var url = res.tempFilePaths[0];
						_this.toupload(url, 2);
					}
				});
			},

			/**
			 * 语音方法
			 */
			// 打开底部面板
			showMenu() {
				this.isShowMenu = !this.isShowMenu
				this.isShowVoice = false
			},
			showVoice() {
				this.isShowVoice = !this.isShowVoice
				this.isShowMenu = false;
			},

			//录音开始
			voiceBegin(e) {
				this.voiceTis = '松开 发送';
				if (e.touches.length > 1) {
					return;
				}
				this.initPoint.Y = e.touches[0].clientY;
				this.initPoint.identifier = e.touches[0].identifier;
				this.RECORDER.start({
					format: "mp3"
				}); //录音开始,
			},
			//录音开始回调 设置UI效果
			recordBegin(e) {
				this.recording = true;
				this.recordLength = 0;
				this.recordTimer = setInterval(() => {
					this.recordLength++;
				}, 1000)
			},
			// 录音被打断
			voiceCancel() {
				this.recording = false;
				this.recordTis = '手指上滑 取消发送'
				this.willStop = true; //不发送录音
				this.RECORDER.stop(); //录音结束
			},
			// 录音中(判断是否触发上滑取消发送)
			voiceIng(e) {
				if (!this.recording) {
					return;
				}
				let touche = e.touches[0];
				//上滑一个导航栏的高度触发上滑取消发送
				if (this.initPoint.Y - touche.clientY >= uni.upx2px(100)) {
					this.willStop = true;
					this.recordTis = '松开手指 取消发送'
				} else {
					this.willStop = false;
					this.recordTis = '手指上滑 取消发送'
				}
			},
			// 结束录音
			voiceEnd(e) {
				if (!this.recording) {
					return;
				}
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.RECORDER.stop(); //录音结束
			},
			//录音结束(回调文件)
			recordEnd(e) {
				clearInterval(this.recordTimer);
				if (!this.willStop) {
					// let msg = {
					// 	length: 0,
					// 	url: e.tempFilePath
					// }
					// let min = parseInt(this.recordLength / 60);
					// let sec = this.recordLength % 60;
					// min = min < 10 ? '0' + min : min;
					// sec = sec < 10 ? '0' + sec : sec;
					// msg.length = min + ':' + sec;
					this.toupload(e.tempFilePath, 3)
				} else {
					console.log('取消发送录音');
				}
				this.willStop = false;
			},
			playVoice(msg) {
				this.AUDIO.src = msg;
				this.$nextTick(function() {
					this.AUDIO.play();
				});
			},

			/**
			 * 语音方法
			 */

			/* 上传文件 */
			toupload: function(url, index) {
				var _this = this;
				_this.$uapi.apifile('api/v1/upload',{file:url}).then(res=>{
					_this.uploadurl = JSON.parse(res.data).data.fileUrl;
					_this.sendMsg(index);
				})
			}

		}
	}
</script>

<style lang="scss">
	page {
		background: #F7F7F7;
		font-family: Source Han Sans CN;
		font-weight: 400;
		line-height: 54upx;
		height: 100%;
	}

	/* 语音提示框 */
	.voice-container {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		width: 400upx;
		height: 400upx;
		background: rgba(51, 51, 51, 1);
		opacity: 0.5;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.iconyuyin1 {
		font-size: 150upx;
		color: #FFFFFF;
	}

	.voice-time {
		color: #FFFFFF;
		font-size: 40upx;
		line-height: 68upx;
	}

	/* 父容器 */
	.container {
		height: 100%;
		display: flex;
		flex-direction: column;
	}

	/* 聊天信息滚动框 */
	.msg-content {
		width: 100%;
		flex: 1;
		overflow: auto;
		padding-bottom: 28upx;
	}

	.msg-content .content {
		padding: 0 30upx;
	}


	/* 左边客服消息 */
	.msg-left {
		display: flex;
		align-items: flex-start;
		margin-top: 48upx;

		.msg_content {
			display: flex;
			justify-content: flex-start;
			margin-left: 20upx;

			.item {
				top: 30upx;
				height: 0upx;
				width: 0upx;
				position: relative;
				border: 10upx solid;
				border-color: transparent #fff transparent transparent;
			}

			.message {
				font-size: 32upx;
				background: #FFFFFF;
				border-radius: 8upx;
				padding: 12upx;
				color: #333333;
				text-align: left;
				max-width: 480upx;
				word-break:break-all;

			}

			.img {
				max-width: 450upx;
			}

			.vediomessage {
				font-size: 32upx;
				background: #FFFFFF;
				border-radius: 8upx;
				padding: 12upx;
				display: flex;
				justify-content: flex-start;

				// 模拟录音音效动画
				@keyframes volatility {
					0% {
						background-position: 10% 0%;
					}

					20% {
						background-position: 20% 0%;
					}

					30% {
						background-position: 30% 0%;
					}

					40% {
						background-position: 40% 0%;
					}

					50% {
						background-position: 50% 0%;
					}

					70% {
						background-position: 60% 0%;
					}

					80% {
						background-position: 70% 0%;
					}

					90% {
						background-position: 80% 0%;
					}

					100% {
						background-position: 100% 0%;
					}
				}

				.iconfont {
					background-image: linear-gradient(to right, #f09b37, #fff 100%);
					background-size: 100% 100%;
					animation: volatility 1.5s ease -1.5s infinite alternate;
					-webkit-background-clip: text;
					-webkit-text-fill-color: transparent;
					color: #f09b37;
				}
			}
		}
	}

	.msg-right {

		display: flex;
		justify-content: flex-end;
		margin-top: 48upx;

		.msg_content {
			display: flex;
			justify-content: flex-end;
			margin-right: 20upx;

			.item {
				top: 30upx;
				height: 0upx;
				width: 0upx;
				position: relative;
				border: 10upx solid;
				border-color: transparent transparent transparent #fff;
			}

			.message {
				font-size: 32upx;
				background: #FFFFFF;
				border-radius: 8upx;
				padding: 12upx;
				color: #333333;
				text-align: left;
				max-width: 480upx;
				word-break:break-all;
			}

			.img {
				max-width: 450upx;
			}

			.vediomessage {
				font-size: 32upx;
				background: #FFFFFF;
				border-radius: 8upx;
				padding: 12upx;
				display: flex;
				justify-content: flex-start;
			}
		}


	}


	// .msg-right .item {
	// 	position: absolute;
	// 	left: -32upx;
	// 	top: 50%;
	// 	border: 10upx solid;
	// 	border-color: transparent transparent transparent #00D5A2;
	// 	transform: translateY(-50%) scaleY(.7) scaleX(1.2);
	// }

	.model-flex {
		align-items: flex-start;
	}

	/* 消息样式 */



	.customer-message {
		background: #00D5A2;
		color: #FFFFFF;
	}

	/* 头像 */
	.avatar {
		width: 80upx;
		height: 80upx;
		background: #FFFFFF;
		border-radius: 50%;
		position: relative;
	}

	/* 客服头像 */
	.avatar image {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		display: block;
		width: 46upx;
		height: 48upx;
		border-radius: 50%;
	}

	/* 客户头像 */
	.customerAvatar image {
		width: 76upx;
		height: 76upx;
	}

	/* 功能模块消息框 */
	.model-message {
		width: 480upx;
		background: #FFFFFF;
		font-size: 32upx;
		align-items: flex-start;
		margin: 0 32upx;
	}

	.model-message .title {
		display: block;
		color: #333333;
		margin: 26upx 0 24upx 28upx;
	}

	.model-message .message-list {
		display: flex;
		align-items: center;
		margin-bottom: 44upx;
		height: 30upx;
	}

	.model-message .message-list .dian {
		display: inline-block;
		width: 14upx;
		height: 14upx;
		background-color: #333333;
		border-radius: 50%;
		margin: 0 16upx 0 28upx;
	}

	.model-message .message-list .message {
		font-size: 30upx;
		color: #00D5A2;
		margin: 0;
		padding: 0;
	}

	.feedback {
		display: flex;
		color: #333333;
		margin-left: 16upx;
		margin-bottom: 42upx;
	}

	.feedback text {
		margin-right: 20upx;
	}

	.feedback navigator {
		color: #00D5A2;
	}

	/* 右边客户端信息 */
	.msg-right {
		display: flex;
		justify-content: flex-end;
		align-items: flex-start;
		margin-top: 48upx;
	}

	.time {
		display: flex;
		justify-content: center;
		padding-top: 30upx;
	}

	.time text {
		font-size: 24upx;
		color: #999999;
	}

	.sendContent {
		float: right;
		margin-right: 30upx;
		margin: 44upx 30upx 44upx 0;
	}

	.information {
		width: 750upx;
		height: 120upx;
		background: rgba(247, 247, 247, 1);
		box-shadow: 0px -1px 6px rgba(0, 0, 0, 0.08);
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.information image {
		width: 60upx;
		height: 60upx;
	}

	.iconyuyin {
		margin-left: 30upx;
		font-size: 60upx;
		color: #666666;
	}

	.iconxinjianbijibenjiahao {
		font-size: 60upx;
		color: #666666;
	}

	/* 输入框 */
	.chat {
		width: 380upx;
		height: 68upx;
		background: #FFFFFF;
		border-radius: 8upx
	}

	/* 语音按钮 */
	.voice-button {
		width: 380upx;
		height: 68upx;
		border-radius: 8upx;
		background: rgba(229, 229, 229, 1);
		text-align: center;
		line-height: 68upx;
		color: #666666;
	}

	.send {
		width: 80upx;
		height: 68upx;
		border-radius: 8upx;
		background: #FF9900;
		line-height: 68upx;
		text-align: center;
		color: #FFFFFF;
		font-size: 32upx;
		margin-right: 30upx;
	}

	/* 点击加显示 */
	.addShow {
		width: 750upx;
		height: 234upx;
		background: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: space-between;
		justify-content: flex-start;
		color: #333333;
		font-size: 26upx;
		text-align: center;
	}

	.addShowImg {
		margin-left: 64upx;
	}

	.addShowPhoto {
		margin-left: 126upx;
	}

	.iconxiangce {
		font-size: 57upx;
		color: #00D5A2;
	}

	.iconpaishe {
		font-size: 56upx;
		color: #00ACFE;
	}


	.hidden {
		display: none !important;
	}

	.record {
		width: 40vw;
		height: 40vw;
		position: fixed;
		top: 55%;
		left: 30%;
		background: rgba(0, 0, 0, 0.6);
		border-radius: 20upx;

		.ing {
			width: 100%;
			height: 30vw;
			display: flex;
			justify-content: center;
			align-items: center;

			// 模拟录音音效动画
			@keyframes volatility {
				0% {
					background-position: 0% 130%;
				}

				20% {
					background-position: 0% 150%;
				}

				30% {
					background-position: 0% 155%;
				}

				40% {
					background-position: 0% 150%;
				}

				50% {
					background-position: 0% 145%;
				}

				70% {
					background-position: 0% 150%;
				}

				80% {
					background-position: 0% 155%;
				}

				90% {
					background-position: 0% 140%;
				}

				100% {
					background-position: 0% 135%;
				}
			}

			.iconfont {
				background-image: linear-gradient(to bottom, #f09b37, #fff 50%);
				background-size: 100% 200%;
				animation: volatility 1.5s ease-in-out -1.5s infinite alternate;
				-webkit-background-clip: text;
				-webkit-text-fill-color: transparent;
				font-size: 150upx;
				color: #f09b37;
			}
		}

		.cancel {
			width: 100%;
			height: 30vw;
			display: flex;
			justify-content: center;
			align-items: center;

			.iconfont {
				color: #fff;
				font-size: 150upx;
			}
		}

		.tis {
			width: 100%;
			height: 10vw;
			display: flex;
			justify-content: center;
			font-size: 28upx;
			color: #fff;

			&.change {
				color: #f09b37;
			}
		}
	}
</style>
